import Vue from 'vue'
import Vuex from 'vuex'
import { api } from '@/api'
import QueryString from 'query-string'
import { getAccountid,getFriendid,getChatid } from '@/lib/data-translate'
import config from '@/config'
import pinyin from '@/lib/pinyin'
import { kf_key } from '@/config'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    websocket: null,
    manager: {
      quickReplies: []
    },
    currentMessages: [],
    messages: {},
    currentService: {},
    currentUser: {},
    services: [
    ],
    chatList:{
      list:[]
    },
    friendList:{list:[]}, // 针对UI显示好友列表

    // 列表中的 accoutid friendid 等并不具有唯一性，集合全部使用id
    uistate:{  // ui状态
      adminid:-1,
      accountid:-1,
      chatid:-1,
      grouptab:-1,
      friendid:-1
    },

    accountListMap:{
      adminid:[],
    },
    friendListMap:{
      accountid:[]
    },
    chatListMap:{
      accountid:[]
    },
    messageListMap:{
      chatid:[]
    },

    groupMemberList:{},
    adminMap:{},
    accountMap:{},
    friendMap:{},
    chatMap:{},
    messageMap:{},
    groupMemberMap:{
      'csid+wxid+groupid+friendwxid':{}
    },
  },
  mutations: {
    // 管理员账号
    setAdminMap(state,data){
      state.adminMap[data.id] = { ...state.adminMap[data.id],...data}
    },
    delAdminMap(state,data){
      state.adminMap[data.id] = undefined
      delete state.adminMap[data.id]
    },
    clearAdminMap(state,data){
      state.adminMap = undefined
      delete state.adminMap
    },

    // 客服账号
    setAccountMap(state,data){
      let _accountMap = {}
      data.forEach(item=>{
        _accountMap[item.id]=item
      })
      state.accountMap = {...state.accountMap,..._accountMap}
      state.services = Object.values(state.accountMap)
    },
    updateAccountMap(state,data){
      state.accountMap[data.id] = {...state.accountMap[data.id],...data}
      state.services = Object.values(state.accountMap)
    },
    addAccountMap(state,data){
      let _account = {}
      _account[data.id] = data;
      state.accountMap = { ...state.accountMap,..._account }
      state.services = Object.values(state.accountMap)
    },
    delAccountMap(state,data){
      state.accountMap[data.id] = undefined
      state.services = Object.values(state.accountMap)
    },
    setAccountListMap(state,data){
      const _accountList = data.map(item=>item.id)
      const _csid = data[0].csid;
      const _accountListMap = state.accountListMap[_csid]||[]
      state.accountListMap[_csid] = Array.from(new Set([..._accountListMap,..._accountList]))
    },
    delAccountListMap(state,data){
    },
    // 好友账号集合
    setFriendMap(state,data){
      let _friendMap = {}
      data.forEach(item=>{ _friendMap[item.id] = item })
      state.friendMap = {...state.friend,..._friendMap}
    },
    updateFriendMap(state,data){
      // todo 会不会更新列表
      state.friendMap[data.id] = { ...state.friendMap[data.id],...data }
    },
    addFriendMap(state,data){
      let _friend = {}
      // const account = Object.values(state.accountMap).filter(item=>item.wxid === wxaccount)[0]
      _friend[data.id] = data;
      state.friendMap = {...state.friendMap,..._friend}
    },
    setFriendListMap(state,data){
      const _friendList = data.map(item=>item.id)
      if((data||[]).length === 0)return;
      // 查找accountid字段
      const _accountid = data[0].accountid
      const _oldFriendListMap = state.friendListMap[_accountid]||[]
      let _friendListMap = {}
      _friendListMap[_accountid] = Array.from(new Set([..._oldFriendListMap,..._friendList] ))

      state.friendListMap = {...state.friendListMap,..._friendListMap}

    },
    addFriendListMap(state,data){

    },
    // 会话集合
    setChatMap(state,data){
      let _chatMap = {}
      data.forEach(item=>{
        if(item.id){
          item['chars'] = pinyin.getFullChars(''+item.friendremark+item.friendwxid+item.friendNick).toLocaleLowerCase()
          _chatMap[item.id] = item
        }
      })
      state.chatMap = {...state.chatMap,..._chatMap}
    },
    updateChatMap(state,data){
      if(data.id){
        if(data.friendremark+data.friendwxid+data.friendNick){
          data['chars'] = pinyin.getFullChars(''+data.friendremark+data.friendwxid+data.friendNick).toLocaleLowerCase()
        }
        state.chatMap[data.id] = { ...state.chatMap[data.id],...data }
      }

    },
    plusChatNoReadCnt(state,data){
      if(data.id){
        const noReadCnt = +data.noReadCnt||0
        const chat = state.chatMap[data.id]
        const oldNoReadCnt = +chat.noReadCnt||0
        chat.noReadCnt = noReadCnt+oldNoReadCnt
      }
      if(data.accountid){
        const accountid = data.accountid
        const account = state.accountMap[accountid]
        const noReadCnt = +data.noReadCnt||0
        const oldNoReadCnt = +account.noReadCnt||0
        account.noReadCnt = noReadCnt+oldNoReadCnt
      }
    },
    subChatNoReadCnt(state,data){
      let number = 0;
      if(data.id){
        const chat = state.chatMap[data.id]
        if(chat){
          number = chat.noReadCnt||0
          chat.noReadCnt = 0
        }

      }
      if(data.accountid){
        const accountid = data.accountid
        const account = state.accountMap[accountid]
        const oldNoReadCnt = +account.noReadCnt||0
        account.noReadCnt = Math.max(0,oldNoReadCnt - number)
      }
    },

    addChatMap(state,data){
      if(data.id){
        data['chars'] = pinyin.getFullChars(''+data.friendremark+data.friendwxid+data.friendNick).toLocaleLowerCase()
        state.chatMap[data.id] = data
      }

    },
    delChatMap(state,data){
      state.chatMap[data.id] = undefined
    },
    setChatListMap(state,data){
      const _chatListMap = data.map(item=>item.id)
      if(data.length===0)return
      const _accountid = data[0].accountid
      if(!_accountid)return;
      const _oldList = state.chatListMap[_accountid] || []
      let _chatList={}
      _chatList[_accountid] = Array.from(new Set([..._oldList,..._chatListMap]))

      state.chatListMap = {...state.chatListMap,..._chatList}
    },
    delChatListMap(state,data){
      const _chatid = data.id
      const _idx = state.chatListMap[_accountid].indexOf(_chatid)
      state.chatListMap[_accountid].splice(_idx,1)
    },
    removeChatListMapByChat(state,chat){
      const { id,accountid } = chat
      const idx = state.chatListMap[accountid].indexOf(id)
      if(idx>-1){
        state.chatListMap[accountid].splice(idx,1)
        if(state.uistate.chatid === id)state.uistate.chatid=-1
      }
    },
    // 消息集合
    setMessageMap(state,data){
      let _messageMap = {}
      data.forEach(item=>{
        _messageMap[item.id] = item
      })
      state.messageMap = {...state.messageMap,..._messageMap}
    },
    addMessageMap(state,data){
      let _message = {}
      state.messageMap[data.id||data.msgid] = data
    },
    updateMessageMap(state,data){
      state.messageMap[data.id] = {...state.messageMap[data.id],...data}
    },
    delMessageMap(state,data){
      state.messageMap[data.id] = undefined
    },
    setMessageListMap(state,data ){
      const _messageList = data.map(item=>item.id)
      if(!data[0])return
      const _chatid = data[0].chatid
      let _messageListMap = {}
      const _oldList = state.messageListMap[_chatid]||[]
      _messageListMap[_chatid] = Array.from(new Set( _oldList.concat(_messageList.reverse()))) // 列表反向
      state.messageListMap = { ...state.messageListMap,..._messageListMap }
    },
    addMessageListMap(state,data){
      const chatid = data.chatid
      const id = data.id || data.msgid
      if(state.messageListMap[chatid] instanceof Array ){
        state.messageListMap[chatid].unshift(id)
      }else{
        let newitem = {}
        newitem[chatid] = [id]
        state.messageListMap = { ...state.messageListMap,...newitem }
      }
    },
    updateMessageListMap(state,data){
      const { chatid,msgid } = data;
      let idx = state.messageListMap[chatid].indexOf(+msgid)
      if(idx<0)idx = state.messageListMap[chatid].indexOf(data.id)
      if(idx>=0){
        state.messageListMap[chatid].splice(idx,1,data.id)
      }else{
        state.messageListMap[chatid].unshift(data.id)
      }

    },
    // 群成员列表
    setGroupMemberList(state,{data,params}){
      const { groupid } = params
      state.groupMemberList[groupid] = data
    },
    setGroupMemberMap(state,{data,params}){
      const { csId,wxAccount,groupNo } = params
      const key = csId+'_'+wxAccount+'_'+groupNo
      let memberMap = {}
      const list = data.map(item=>{
        let _key = key+'_'+item.wxid
        memberMap[_key] = item
        return _key
      })
      state.groupMemberMap = {...state.groupMemberMap,...memberMap}
      state.groupMemberList[key] = list
    },
    // uistate
    updateUIState(state,data){
      state.uistate = {...state.uistate,...data}
    },

    initManager(state, info) {
      state.manager = {...state.manager, ...info}
    },
    initServices(state, services) {
      state.services = services
    },
    setCurrentService(state, service) {
      state.currentService = service
    },
    setCurrentMessages(state, {messages, wxaccount}) {
      state.currentMessages = messages
      state.messages[wxaccount] = messages
    },
    addMessage(state,friend){
      const hasFriend = state.currentMessages.filter(f=>f.wxid==friend.wxid)[0]
      if (!hasFriend) {
        state.currentMessages.unshift(friend)
      }
    },
    removeMessage(state,params){
      const { accountWxId, friendWxid } = params
      let index;
      state.messages[accountWxId].forEach((item,idx)=>{ if(item.friendwxid === friendWxid)index=idx })
      state.messages[accountWxId].splice(index,1)
    },
    // 返回聊天列表
    setChatList(state,{data, params}){
      // todo 需要判断当前聊天对象
      if(+params.pageNo === 1){
        state.chatList = { params,list:data }
      }else{
        const list = [...data,...state.chatList.list]
        state.chatList = { params,list }
      }
    },
    clearChatList(state){
      state.chatList.list.splice(0,state.chatList.list.length)
    },
    //  添加消息
    addChat(state,{ chat,friend }){
      const { friendwxid,wxaccount } = friend;
      // 判断当前会话 是否加入list
      state.chatList.list.push(chat)
      state.messages[wxaccount].forEach((item,index)=>{
        if(item.wxid === friendwxid){
          item.lastMessage = chat.content
          state.messages[wxaccount].splice(index,1,item)
        }
      })
    },

    // 修改消息状态
    updateChat(state,data ){
      const { msgid,csid } = data;
      state.chatList.list.forEach((item,index)=>{
        if(+msgid === +item.msgid){
          item = {...item,...data}
          state.chatList.list.splice(index,1,item)
        }
      })
    },


    // 账号在线状态变化
    changeOnline(state,data){
      const { account , onlineTime } = data
      Object.values(state.accountMap).forEach(item=>{
        if(item.wxid === account){
          state.accountMap[item.id].logintime = onlineTime * 1000
        }
      })
      state.accountMap
    },
    // 双登踢出
    loginSafe(){},

    setCurrentUser(state, user) {
      state.currentUser = user
    },
    changeMessageInfo(state, message) {
      state.currentUser = message
      state.currentMessages = state.messages.map(m=>{
        if (m.wxid == message.wxid) {
          return message
        }
        return m
      })
      state.messages[state.currentService.wxid] = state.currentMessages
    },
    pushReply(state, reply){
      state.manager.quickReplies.push(reply)
    },
    changeGroupStatus(state, { csid, groupId, data }) {
      state.services = state.services.map(s=>{
        if (s.wxid == csid) {
          s.messages = s.messages.map(m=>{
            if (m.wxid == groupId) {
              return {
                ...m,
                ...data
              }
            }
            return m
          })
          return s
        }
        return s
      })
    },
    dismissGroup(state, {csid, groupId}) {
      state.services = state.services.map(s=>{
        if (s.wxid == csid) {
          s.messages = s.messages.filter(m=>m.wxid != groupId)
          return s
        }
        return s
      })
    },
    // 好友相关
    // 好友列表
    setFriendList(state,{data,params}){
      state.friendList = { params,list:data }
    },
    // 清除界面显示
    clearFriendList(state){
      state.friendList.list.splice(0,state.friendList.list.length)
    },
    // websocket 相关
    websocketUpdate(state, websocket){
      state.websocket = websocket
    },
    websocketOnopen(state,data){
      if(!this.timer)
      this.timer = setInterval(()=> {
        state.websocket.send(JSON.stringify({
          'heart': true
        }))
      }, 30000)

      console.log('webSocket OPEN',state,data)
    },
    websocketOnerror(state,data){
      console.log('webSocket ERROR',state,data)
      if(this.timer)clearInterval(this.timer)
      state.websocket = false
    },
    websocketClose(state,data){
      console.log('webSocket CLOSE',state,data)
      if(this.timer)clearInterval(this.timer)
      state.websocket = false
    },
  },
  actions: {
    login({state, commit, dispatch},params){
      const {username,password} = params
      return api.user.login({
        username,
        password
      }).then(data=>{
        commit('setAdminMap',data)
        commit('updateUIState',{ adminid:data.id })
        commit('initManager', data)
        dispatch('initWebSocket', { user_id: data.id})
        dispatch('initNotification')
        return dispatch('initAccounts', data.id)
      }).catch(e=>{
        return Promise.reject(e)
      })

    },
    logout({state, commit, dispatch},params){
      dispatch('destroyWebSocket')
      console.log(kf_key)
      sessionStorage.removeItem(btoa(kf_key))

      commit('updateUIState',{ adminid:-1 })
    },
    init({state, commit, dispatch}) {
      return api.user.login({
        username: 'testkf',
        password: '123456'
      }).then(data=>{
        commit('setAdminMap',data)
        commit('updateUIState',{ adminid:data.id })
        commit('initManager', data)
        dispatch('initWebSocket', { user_id: data.id})
        dispatch('initNotification')
        return dispatch('initAccounts', data.id)
      }).catch(e=>{
        return Promise.reject(e)
      })
    },
    initAccounts({commit}, csid) {
      return api.user.list({
        csid
      }).then(data=>{
        data = data.map(item=>{
          return {
            ...item,
            name: item.account,
            gender: item.gender,
            avatar: item.avatar,
            whatsup: item.signature || '',
          }
        })
        commit('setAccountMap',data)
        commit('setAccountListMap',data)
        commit('initServices', data)
        commit('setCurrentService', data[0] || {})
      }).catch(e=>{
        return Promise.reject(e)
      })
    },
    initGroups({commit}, params) {
      return api.friend.chatFriends(params)
        .then(data=>{
          let messages = []
          messages = data.map(item=>{
            return {
              name: item.friendNick || 'unknown',
              avatar: item.friendavatar || '',
              wxid: item.friendwxid || '',
              type: item.msgtype || 'user',
              lastMessage: item.pushcontent,
              mark: item.friendremark || '',
              decline: item.showstatus ? false : true,
              ...item
            }
          })
          if(params.wxaccount)
          commit('setCurrentMessages', {
            wxaccount: params.wxaccount,
            messages
          })
      }).catch(e=>{
        return Promise.reject(e)
      })
    },
    initWebSocket({state,commit,dispatch}, params = {}){
      if(!params.user_id)return;
      if(state.websocket){
        state.websocket.close()
        state.websocket = null
      }

      const query = QueryString.stringify(params)
      // const wsuri =  "ws://192.168.1.150:8080/ws/server?"+query;//ws地址
      const wsuri =  config.wsUrl+"?"+query;//ws地址
　　　 const websocket = new WebSocket(wsuri);
　　　 websocket.onopen = e =>commit('websocketOnopen',e);
      websocket.onerror = e =>commit('websocketOnerror',e);
      websocket.onmessage = e =>dispatch('websocketOnmessage',e);
      websocket.onclose = e =>commit('websocketClose',e);
      commit('websocketUpdate', websocket )
    },
    destroyWebSocket({state,commit,dispatch}) {
      clearInterval(this.timer)
      let websocket = state.websocket
      if(websocket){
        websocket.onopen = e =>{};
        websocket.onerror = e =>{};
        websocket.onmessage = e =>{};
        websocket.onclose = e =>{};
        websocket.close()
      }
      state.websocket = null

    },
    websocketOnmessage({state,commit,dispatch},{data}){
      try{
        const wsdata = JSON.parse(data)||{}
        if(+wsdata.opType === 1){
          dispatch('sendChatResult',wsdata)
        }else if(+wsdata.opType === 2){
          dispatch('receiveChat',wsdata)
          dispatch('notice',{title:'来自'+ (wsdata.friend.friendnick||wsdata.friend.groupname||'群聊天') +'的新消息',body:'点击查看' })
        }else if(+wsdata.opType === 3){
          // commit('sendChatResult',wsdata)
        }else if(+wsdata.opType === 4){
          commit('changeOnline',wsdata)
        }else if(+wsdata.opType === 5){
          commit('loginSafe',wsdata)
        }else if(+wsdata.opType === 6){

        }else if(+wsdata.opType === 7){
          window.timelineCallback && window.timelineCallback(wsdata)  // 朋友圈
        }else if(+wsdata.opType === 8){
          const csid = this.state.uistate.adminid;
          window.friendSync && window.friendSync(wsdata)
          if(csid)dispatch('initAccounts', csid )
          // 同步通讯录
        }
        console.log('webSocket MESSAGE',state,wsdata)
      }catch(e){}



    },
    // 发送聊天返回数据
    sendChatResult({state,commit,dispatch},data){
      let { msgId,chat } = data;
      const { wxaccount , friendwxid,csid } = chat;
      const accountid = getAccountid(state.accountMap,csid,wxaccount)
      const friendid = getFriendid(state.friendMap,csid,wxaccount,friendwxid)
      const chatid = getChatid(csid,accountid,friendwxid)
      chat.chatid = chatid
      chat.accountid = accountid
      chat.friend = friendid

      if(chatid === 0)return; // 列表并未初始化，请求时从服务器拉取
      commit('addMessageMap',chat)
      commit('updateMessageListMap',chat)
      commit('updateChatMap',{id:chatid,content:chat.content,realFromNick:''})

    },
    wsSend({state,commit,dispatch}, params){
      const websocket = state.websocket;
      const body = JSON.stringify(params)
      if(websocket){
        websocket.send( body )
      }
    },
    // 接收聊天消息
    receiveChat({state,commit,dispatch},{chat,friend}){
      // todo 这些id都需要整理数据
      const { adminid }  = state.uistate
      const csid = adminid
      chat.csid = csid
      friend.csid = csid

      const { wxaccount,friendwxid } = chat;
      const accountid = getAccountid(state.accountMap,csid,wxaccount)
      const friendid = getFriendid(state.friendMap,csid,wxaccount,friendwxid)
      const chatid = getChatid(csid,accountid,friendwxid)

      chat.chatid = chatid
      chat.accountid = accountid
      chat.friendid = friendid
      // friend avater 字段给错了
      delete chat.avatar
      dispatch('addChatByMessage',chat)
      commit('addMessageMap',chat)
      commit('addMessageListMap',chat)
      if(chat.friendwxid.indexOf('@chatroom')){
        commit('updateChatMap',{
          id:chatid,content:chat.content,
          realFromHeadImg:chat.realFromHeadImg,realFromNick:chat.realFromNick,realFromWxId:chat.realFromWxId,
          friendNick:chat.friendNick
        })
      }else{
        commit('updateChatMap',{id:chatid,content:chat.content})
      }

      if(state.uistate.chatid !== chatid){
         commit('plusChatNoReadCnt',{id:chatid,noReadCnt:1,accountid})
      }
    },
    sendChatReaded({state,commit,dispatch}, params){
      // dispatch('wsSend',params) // 向服务器发送已读
      const { wxAccount,friendAccount,csId } = params;
      const accountid = getAccountid(state.accountMap,csId,wxAccount)
      const chatid = getChatid(csId,accountid,friendAccount)

      return api.chat.readChat(params)
        .then(data=>{
          commit('subChatNoReadCnt',{ id:chatid,accountid }) // 更改本地消息状态
        }).catch(e=>{
          return Promise.reject(e)
        })

    },
    // 会话聊天
    requestChatMap({ state,commit },params){
      return api.friend.chatFriends(params)
        .then(data=>{
          if(data[0]){
            const { csid,wxaccount } = params
            const accountid = getAccountid(state.accountMap,csid,wxaccount)
            data.forEach(item=>{
              const friendid = getFriendid(state.friendMap,csid,wxaccount,item.friendwxid)
              const id = getChatid(csid,accountid,item.friendwxid)

              item.id=id;
              item.accountid=accountid;
              item.friendid=friendid
              if(!friendid)return;
            })
            commit('setChatMap',data)
            commit('setChatListMap',data)
            return data
          }

      }).catch(e=>{
        return Promise.reject(e)
      })
    },
    // 会话群成员
    requestGroupMember({ state,commit },params){
      return api.group.members(params)
        .then(data=>{
          // commit('setGroupMemberList',{params,data})
          commit('setGroupMemberMap',{params,data})
        })
        .catch(e=>{
          return Promise.reject(e)
        })
    },
    // 聊天消息列表
    requestMessageMap({commit,state}, params){
      return api.chat.chatList(QueryString.stringify(params))
      .then(data=>{
        if(data[0]){
          const {
            accountWxId ,
            chatid,
            csId,
            friendWxid,//: "22909349758@chatroom"
          } = params
          const wxaccount = accountWxId
          const csid = csId
          const friendwxid = friendWxid
          // const { wxaccount,friendwxid,csid,groupno } = data[0]||{}
          const accountid = getAccountid(state.accountMap,csid,wxaccount)
          const friendid = getFriendid(state.friendMap,csid,wxaccount,friendwxid)
          // const chatid = getChatid(csid,accountid, friendwxid)
          data.forEach(item=>{
            item.chatid = chatid;
            item.accountid = accountid;
            item.friendid = friendid,
            item.csid = csid
          })
        }
        commit('setMessageMap', data)
        commit('setMessageListMap', data)
        return data
      }).catch(e=>{
        return Promise.reject(e)
      })
    },
    requestFriendMap({commit,state}, params){
      return api.friend.list(params)
      .then(data=>{
        if(data[0]){
          const { wxaccount,csid } = params
          const accountid = getAccountid(state.accountMap,csid,wxaccount)
          data.forEach(item=>{ item.accountid = accountid  })
        }
        commit('setFriendMap',data)
        commit('setFriendListMap',data)
      }).catch(e=>{
        return Promise.reject(e)
      })
    },
    addChatByMessage({commit,state},data){
      const {csid,accountid,friendid,chatid} = data;
      let _chat = state.chatMap[chatid]
      data['chars'] = pinyin.getFullChars(''+data.friendremark+data.friendwxid+data.friendNick).toLocaleLowerCase()
      if(_chat){ // 已经存在的会话
        Object.keys(data).forEach(key=>{
          if(data[key] === null){
            delete data[key]
          }
        })
        //state.chatMap[chatid] = {..._chat,...data}
      }else{
        state.chatMap[chatid] = data
      }
      if(accountid){
        const _idx = state.chatListMap[accountid].indexOf(chatid)
        if(_idx>-1){
          state.chatListMap[accountid].splice(_idx,1)
        }
        state.chatListMap[accountid].unshift(chatid)
      }
    },
    addChatByFriend({commit,state},data){
      // 客服id 好友自增id 客服账号 wxid 好友wxid
      const {csid,wxaccount,friendwxid} = data;
      const accountid = getAccountid(state.accountMap,csid,wxaccount)
      console.log(state.accountMap,csid,wxaccount)
      const chatid = getChatid(csid,accountid,friendwxid)
      let _chat = state.chatMap[chatid]
      data['chars'] = pinyin.getFullChars(''+data.friendremark+data.friendwxid+data.friendNick).toLocaleLowerCase()
      if(_chat){ // 已经存在的会话
        state.chatMap[chatid] = {..._chat}
      }else{
        data.id = chatid
        state.chatMap[chatid] = data
      }
      if(accountid){
        const _idx = state.chatListMap[accountid].indexOf(chatid)
        if(_idx>-1){
          state.chatListMap[accountid].splice(_idx,1)
        }
        state.chatListMap[accountid].unshift(chatid)
      }
      /**
       *
       * avatar: "http://wx.qlogo.cn/mmhead/ver_1/B9YJdL9k4z56PCQF3TyzFSh9cyxQK8e9MggTOz5R4GJ0UKB2gQ4CDr7Tk8bnM2fqP3lNV18MPx9cWibSKsicC8xdzwzliawJueGOKiavNGU3EPc/132"
          createtime: (...)
          csid: (...)
          friendalias: (...)
          friendnick: (...)
          friendremark: (...)
          friendsex: (...)
          friendsignature: (...)
          friendwxid: (...)
          fromgroupid: (...)
          id: (...)
          istop: (...)
          status: (...)
          updatetime: (...)
          wxaccount: (...)

       */

    },
    // 客服账号设置
    updateWxAccount({commit,state},params){
      return api.user.updateWxAccount(params)
        .then(res=>{
          state.accountMap[params.id] = {...state.accountMap[params.id],...params}
        })
        .catch(e=>{
          return Promise.reject(e)
        })
    },
    // 设置VIP 屏蔽
    setVIP({commit,state}, params){
      return api.chat.topAndStatus(params)
      .then(res=>{
        state.chatMap[params.chatid].isTop = params.isTop
      })
      .catch(e=>{
        return Promise.reject(e)
      })
    },
    setStatus({commit,state}, params){
      return api.chat.topAndStatus(params)
        .then(res=>{
          state.chatMap[params.chatid].showstatus = params.showStatus
        })
        .catch(e=>{
          return Promise.reject(e)
        })
    },

    // params:{ accountWxId:1,friendWxid:1,csId:1,pageNo:0,pageSize:100 }
    getChatList({commit}, params){
      if(params.pageNo === 1)commit('clearChatList')
      return api.chat.chatList(QueryString.stringify(params))
      .then(data=>{
        commit('setChatList', {data, params})
      }).catch(e=>{
        return Promise.reject(e)
      })
    },
    removeChatList({ commit,state }, params){
      const { id } = params;
      const chat = state.chatMap[id]
      if(!chat)return
      const {  csid, friendwxid ,  wxaccount } = chat
      commit('removeChatListMapByChat',chat)
      return api.chat.removeChatList(QueryString.stringify({ csId:csid, accountWxId: wxaccount, friendWxid: friendwxid}))
      .then(data=>{

      }).catch(e=>{
        return Promise.reject(e)
      })
    },
    getFriendList({commit}, params){
      commit('clearFriendList')
      return api.friend.list(params)
      .then(data=>{
        //commit('setFriendMap',data)
        //commit('setFriendListMap',data)
        //commit('setFriendList', {data, params})
      }).catch(e=>{
        return Promise.reject(e)
      })
    },

    // 添加卡片好友
    acceptCard({commit}, params){
      return api.chat.acceptCard(params)
      .then(data=>{
        console.log('发送添加好友卡片请求成功')
      }).catch(e=>{
        return Promise.reject(e)
      })
    },

    /**
     * 通知
     */
    initNotification(){
      window.onfocus = function (ev) {
        window.isFocus = 1
      }
      window.onblur = function (ev) {
          window.isFocus = 0
      }
      // 申请权限
      if (Notification && Notification.permission !== "granted") {
        Notification.requestPermission(function (status) {
            if (Notification.permission !== status) {
                Notification.permission = status;
            }
        });
      }
    },
    // 发送通知
    notice({commit,dispatch},{title, body,onclick=()=>{}}) {
      if (window.isFocus) return;
      var options = {
          dir: "rtl",
          lang: "zh-CN",
          body: body,
      }
      var notification = new Notification(title, options);
      dispatch('autoClose',{notification,onclick})
    },
    autoClose({commit,dispatch},{notification,onclick}) {
      if (typeof notification.time === 'undefined' || notification.time <= 0) {
          notification.close();
      } else {
          setTimeout(function () {
              notification.close();
          }, notification.time);
      }
      notification.addEventListener('click', function () {
          window.focus();
          notification.close();
          onclick()
      }, false)
  }

  }
})
